<?php
/**
 * 账单组Model
 * @author hero
 */
class GroupModel extends BaseModel 
{
	public static $name='`group`';
	public static $primary='g_id';
	
	public function __construct() {
		parent::__construct(CoreFactory::db(),self::$name,self::$primary);
	}
	
	/**
	 * 获取有效的记录
	 * @author solar
	 * @param int $g_id
	 * @return row
	 */
	public function getActive($g_id) {
		return $this->getByField(array('g_id'=>$g_id,'g_status'=>1));
	}
	
	/**
	 * 用户的账单组列表
	 * @author solar
	 * @param int $user_id
	 * @return list
	 */
	public function getListByUser($user_id) {
		$sql = 'SELECT g.*,gu.u_id,gu.is_default FROM `group` AS g
		 RIGHT JOIN `group_user` AS gu ON g.g_id=gu.g_id
		  WHERE gu.u_id='.$user_id.' AND g.g_status=1';
		return $this->db->fetchAll($sql);
	}
		
	/**
	 * 创建账单组
	 * @author solar
	 * @param string $group_name
	 * @return int
	 */
	public function create($group_name) {
		$row['g_name']=$group_name;
		$row['g_quantity']=1;
		$row['g_creator']=CoreFactory::session()->get('user_id');
		$row['g_creator_name']=CoreFactory::session()->get('user_name');
		$row['g_create_time']=time();
		return $this->insert($row);
	}
	
	/**
	 * 是否创建者
	 * @author solar
	 * @param int $group_id
	 * @return boolean
	 */
	public function isCreator($group_id) {
		$row=$this->get($group_id);
		return ($row['g_creator']==CoreFactory::session()->get('user_id')) ? true : false;
	}
	
	/**
	 * 屏蔽账单组
	 * @author solar
	 * @param $group_id
	 * @return int
	 */	
	public function inactive($group_id) {
		return $this->update(array('g_status'=>0),$group_id);
	}
	
	/**
	 * 修改账单组名称
	 * @author solar
	 * @param $group_id
	 * @param $new_name
	 * @return int
	 */	
	public function changeName($group_id,$new_name) {
		return $this->update(array('g_name'=>$new_name),$group_id);
	}
	
	/**
	 * 账单组成员数加1
	 * @author solar
	 * @param int $group_id
	 * @return int
	 */
	public function plusQuantity($group_id) {
		$this->db->query('UPDATE `group` SET g_quantity=g_quantity+1 WHERE g_id='.$group_id.' LIMIT 1');
		return $this->db->affectedRows();
	}
	
	/**
	 * 账单组成员数减1
	 * @author solar
	 * @param int $group_id
	 * @return int
	 */
	public function minusQuantity($group_id) {
		$this->db->query('UPDATE `group` SET g_quantity=g_quantity-1 WHERE g_id='.$group_id.' LIMIT 1');
		return $this->db->affectedRows();
	}
	
}

?>